/*
 * Copyright (c) 2018  菠菜数块链版权所有.
 */
package com.otherTest.bcrypt;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.security.SecureRandom;
import java.util.regex.Pattern;

/**
 * @Description:
 * @author: conceit
 * @Date: 2018/8/16 0016 11:28
 */
public class BcryptPasswordUtils implements BcyptPasswordEncoder {

    private final Log logger = LogFactory.getLog(getClass());
    private final int strength;
    private final SecureRandom random;
    private Pattern BCRYPT_PATTERN = Pattern.compile("\\A\\$2a?\\$\\d\\d\\$[./0-9A-Za-z]{53}");

    public BcryptPasswordUtils() {
        this(-1);
    }

    /**
     * @param strength the log rounds to use, between 4 and 31
     */
    public BcryptPasswordUtils(int strength) {
        this(strength, null);
    }

    /**
     * @param strength the log rounds to use, between 4 and 31
     * @param random   the secure random instance to use
     */
    public BcryptPasswordUtils(int strength, SecureRandom random) {
        if (strength != -1 && (strength < BcryptUtils.MIN_LOG_ROUNDS || strength > BcryptUtils.MAX_LOG_ROUNDS)) {
            throw new IllegalArgumentException("Bad strength");
        }
        this.strength = strength;
        this.random = random;
    }

    public String encode(CharSequence rawPassword) {
        String salt;
        if (strength > 0) {
            if (random != null) {
                salt = BcryptUtils.gensalt(strength, random);
            } else {
                salt = BcryptUtils.gensalt(strength);
            }
        } else {
            salt = BcryptUtils.gensalt();
        }
        return BcryptUtils.hashpw(rawPassword.toString(), salt);
    }

    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        if (encodedPassword == null || encodedPassword.length() == 0) {
            logger.warn("Empty encoded password");
            return false;
        }

        if (!BCRYPT_PATTERN.matcher(encodedPassword).matches()) {
            logger.warn("Encoded password does not look like BCrypt");
            return false;
        }

        return BcryptUtils.checkpw(rawPassword.toString(), encodedPassword);
    }

}
